<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Order extends Model
{
    protected $fillable = [
        'no',
        'address_id',
        'receive_address',
        'receive_province',
        'receive_city',
        'receive_area',
        'receive_contact_name',
        'receive_contact_telephone',
        'status',
        'back_status',
        'express_name',
        'express_code',
        'express_no',
        'back_address_id',
        'back_address',
        'back_address_province',
        'back_address_city',
        'back_address_area',
        'back_contact_name',
        'back_contact_telephone',
        'back_order_time',
        'back_created_at',
        'back_order_no',
        'back_uniquer_request_number',
        'back_express_code',
        'back_express_no',
        'back_confirm_time',
        'send_time',
        'receive_time',
        'real_receive_time',
        'back_express_name',
        'canceled_at'
    ];

    public static $statusMap = [
        -1 => '已取消',
        0  => '待发货',
        1  => '已发货',
        2  => '借阅中',
        3  => '已归还',
    ];

    public static $backStatusMap = [
        0 => '暂无',
        1 => '待快递上门取件 ',
        2 => '待平台收货确认',
        3 => '归还成功',
    ];

    protected static function boot()
    {
        parent::boot();
        // 监听模型创建事件，在写入数据库之前触发
        static::creating(function ($model) {
            // 如果模型的 no 字段为空
            if (!$model->no) {
                // 调用 findAvailableNo 生成订单流水号
                $model->no = static::findAvailableNo();
                // 如果生成失败，则终止创建订单
                if (!$model->no) {
                    return false;
                }
            }
        });
    }

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function items()
    {
        return $this->hasMany(OrderItem::class)->orderBy('id','asc');
    }

    public static function findAvailableNo()
    {
        // 订单流水号前缀
        $prefix = date('YmdHis');
        for ($i = 0; $i < 10; $i++) {
            // 随机生成 6 位的数字
            $no = $prefix.str_pad(random_int(0, 999999), 6, '0', STR_PAD_LEFT);
            // 判断是否已经存在
            if (!static::query()->where('no', $no)->exists()) {
                return $no;
            }
        }
        \Log::warning('find order no failed');

        return false;
    }

    public static function findBackOrderNo()
    {
        // 订单流水号前缀
        $prefix = date('YmdHis');
        for ($i = 0; $i < 10; $i++) {
            // 随机生成 6 位的数字
            $no = $prefix.str_pad(random_int(0, 999999), 6, '0', STR_PAD_LEFT);
            // 判断是否已经存在
            if (!static::query()->where('back_order_no', $no)->exists()) {
                return $no;
            }
        }
        \Log::warning('find order no failed');

        return false;
    }
}
